package zeno.project.springboot.util;

import zeno.project.springboot.entity.User;
import zeno.project.springboot.entity.system.SysUser;

import java.lang.reflect.Field;

/**
 * 类与类对象转换工具，通过反射实现
 * @author zhiyong
 */
public class MappingTool {

    public static void main(String[] args) {
        SysUser sysUser = new SysUser();
        sysUser.setPassword("asd");
        sysUser.setAccount("dwadw");
        User sysUser2 = new User();
        mapper(sysUser, sysUser2);
        System.out.println(sysUser2);
    }

    public static void mapper(Object source, Object target) {
        if (source == null || target == null) {
            throw new NullPointerException();
        }
        // 获得source的字段
        Class<?> sourceClass = source.getClass();
        Field[] sourceFields = sourceClass.getDeclaredFields();
        // 获得target的字段
        Class<?> targetClass = target.getClass();
        Field[] targetFields = targetClass.getDeclaredFields();

        try {
            for (Field src : sourceFields) {
                src.setAccessible(true);
                for (Field tag: targetFields) {
                    tag.setAccessible(true);
                    // 存在相同的字段
                    if (src.getName().equals(tag.getName())) {
                        tag.set(target, src.get(source));
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
